package io.xxx.omni.oss.custom

import com.google.gson.JsonObject
import io.xxx.omni.oss.common.gson
import io.xxx.omni.oss.common.toLocalDateTime
import io.xxx.omni.oss.common.zoneOffset
import io.xxx.omni.oss.domain.Document
import io.xxx.omni.oss.domain.DocumentType
import java.time.LocalDateTime

// 订单
// https://open.kwaixiaodian.com/docs/api?apiName=open.seller.order.pcursor.list&categoryId=43&version=1
@Suppress("unused")
class KsTradeSynchronizer : KsSynchronizer() {

    override val documentType = DocumentType.TRADE

    override fun buildDocuments(context: Context, response: JsonObject): List<Document> {
        return response["orderList"]
            .asJsonArray
            .map {
                val info = it.asJsonObject["orderBaseInfo"].asJsonObject
                Document(
                    info["oid"].toString(),
                    info["status"].toString(),
                    gson.toJson(it),
                    info["createTime"].toLocalDateTime(),
                    info["updateTime"].toLocalDateTime(),
                )
            }
    }

    override fun buildRequest(
        context: Context,
        response: JsonObject?
    ): Pair<String, MutableMap<String, Any>> {
        val (startTime, endTime) = context
        return "open.order.cursor.list" to mutableMapOf(
            "pageSize" to 100,
            "type" to 1,
            "queryType" to 2,
            "beginTime" to startTime.toInstant(zoneOffset).toEpochMilli(),
            "endTime" to endTime.toInstant(zoneOffset).toEpochMilli(),
            "pcursor" to (response?.get("cursor") ?: ""),
        )
    }

    override fun getCursor(response: JsonObject): String {
        return response["cursor"].asString
    }
}